package com.castle.fortress.admin.ai.util;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.castle.fortress.admin.ai.model.enity.CastleConfigAiApi;
import com.castle.fortress.admin.ai.model.enity.QwenRequestBody;
import com.castle.fortress.admin.ai.service.CastleConfigAiApiService;
import com.castle.fortress.admin.ai.service.CastleConfigAiPromptService;
import com.castle.fortress.admin.schedule.model.entity.StudySchedule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.castle.fortress.admin.schedule.model.entity.StudySchedule.getDefaultScheduleList;

/**
 * @author fkrbl
 */
@Component
@Slf4j
public class AIAPIUtil {
    @Resource
    private CastleConfigAiApiService castleConfigAiApiService;
    @Resource
    private CastleConfigAiPromptService castleConfigAiPromptService;
    public static AIAPIUtil aiAPIUtil;

    @PostConstruct
    public void init() {
        aiAPIUtil = this;
    }
    public static void generateQuestion() {

    }

    public static String recommendCourse(String requestBody) {
        CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
        String url = byId.getUrl();
        String headers = byId.getHeaders();
        try {
            log.info("请求体：{}", requestBody);
            Map<String, List<String>> bean = JSONUtil.toBean(headers, Map.class);
            HttpResponse httpResponse = HttpRequest.post(url).header(bean).body(requestBody).executeAsync();
            String body = httpResponse.body();
            log.info("请求结果：{}", body);
            JSONObject responseObject = JSONUtil.parseObj(body);
            String result = responseObject.getByPath("choices[0].message.content", String.class);
            if (result.startsWith("{") && result.endsWith("}")) {
                return result;
            }

            return "\t\t{\n" +
                    "\t\t    \"course_info\": [\n" +
                    "\t\t        {\n" +
                    "\t\t            \"id\": \"1704072134073434114\",\n" +
                    "\t\t            \"course_name\": \"数据库系统原理\",\n" +
                    "\t\t            \"course_description\": \"深入讲解数据库设计、事务管理与存储机制。\",\n" +
                    "\t\t            \"course_recommendation_reason\": \"与你已学的PostgreSQL和Mysql课程形成理论与实践的互补，深化数据库知识体系。\"\n" +
                    "\t\t        },\n" +
                    "\t\t        {\n" +
                    "\t\t            \"id\": \"1705045770590740481\",\n" +
                    "\t\t            \"course_name\": \"Python数据分析与处理\",\n" +
                    "\t\t            \"course_description\": \"利用Python进行数据清洗、分析与可视化。\",\n" +
                    "\t\t            \"course_recommendation_reason\": \"结合你已掌握的Python基础与数据库技能，拓展数据处理实战能力。\"\n" +
                    "\t\t        }\n" +
                    "\t\t    ],\n" +
                    "\t\t    \"summary\": \"以上课程将帮助你深化已有知识，并构建更完整的计算机技术体系，建议根据职业方向选择深入学习。\"\n" +
                    "\t\t}";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static String getStr(String requestBody) {
        CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
        String url = byId.getUrl();
        String headers = byId.getHeaders();
        try {
            log.info("请求体：{}", requestBody);
            Map<String, List<String>> bean = JSONUtil.toBean(headers, Map.class);
            HttpResponse httpResponse = HttpRequest.post(url).header(bean).body(requestBody).executeAsync();
            String body = httpResponse.body();
            log.info("请求结果：{}", body);
            JSONObject responseObject = JSONUtil.parseObj(body);
            return responseObject.getByPath("choices[0].message.content", String.class);
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    public static String generateQuestion(String requestBody) {
        try {
            log.info("请求体：{}", requestBody);
            CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
            return getJSON(requestBody, byId);
        } catch (Exception e) {
            e.printStackTrace();
            return String.format("{error: %s}", e.getMessage());
        }
    }

    public static String getString(String requestBody) {
        try {
            log.info("请求体：{}", requestBody);
            CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
            return getString(requestBody, byId);
        } catch (Exception e) {
            e.printStackTrace();
            return String.format("{error: %s}", e.getMessage());
        }
    }

    public static List<StudySchedule> generateSchedules(String requestBody) {
        try {
            log.info("请求体：{}", requestBody);
            CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
            List<StudySchedule> scheduleList = getScheduleList(requestBody, byId);
            return scheduleList;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取学习计划失败 e-> #{}", e.getMessage());
            return getDefaultScheduleList();
        }
    }
    public static String getScheduleReason(String requestBody) {
        try {
            CastleConfigAiApi byId = aiAPIUtil.castleConfigAiApiService.getById(1);
            String url = byId.getUrl();
            String headers = byId.getHeaders();
            Map<String, List<String>> headerMap = JSONUtil.toBean(headers, Map.class);
            HttpResponse response = HttpRequest.post(url).header(headerMap).body(requestBody).execute();
            String body = response.body();
            log.info("请求结果：{}", body);
            JSONObject responseObject = JSONUtil.parseObj(body);
            return responseObject.getByPath("choices[0].message.content", String.class);
        } catch (Exception e) {
            e.printStackTrace();
            return String.format("{error: %s}", e.getMessage());
        }
    }
    private static String getJSON(String requestBody, CastleConfigAiApi byId) {
        String url = byId.getUrl();
        String headers = byId.getHeaders();
        Map<String, List<String>> headerMap = JSONUtil.toBean(headers, Map.class);
        HttpResponse response = HttpRequest.post(url).header(headerMap).body(requestBody).execute();
        String body = response.body();
        log.info("请求结果：{}", body);
        JSONObject responseObject = JSONUtil.parseObj(body);
        String result = responseObject.getByPath("choices[0].message.content", String.class);
        if (result.startsWith("{") && result.endsWith("}")) {
            return result;
        }
        return "{}";
    }
    private static String getString(String requestBody, CastleConfigAiApi byId) {
        String url = byId.getUrl();
        String headers = byId.getHeaders();
        Map<String, List<String>> headerMap = JSONUtil.toBean(headers, Map.class);
        HttpResponse response = HttpRequest.post(url).header(headerMap).body(requestBody).execute();
        String body = response.body();
        log.info("请求结果：{}", body);
        JSONObject responseObject = JSONUtil.parseObj(body);
        return responseObject.getByPath("choices[0].message.content", String.class);
    }
    private static List<StudySchedule> getScheduleList(String requestBody, CastleConfigAiApi byId) {
        try {
            String url = byId.getUrl();
            String headers = byId.getHeaders();
            Map<String, List<String>> headerMap = JSONUtil.toBean(headers, Map.class);
            HttpResponse response = HttpRequest.post(url).header(headerMap).body(requestBody).execute();
            String body = response.body();
            log.info("请求结果：{}", body);

            // 正确的JSON解析方式
            JSONObject responseObject = JSONUtil.parseObj(body);

            // 获取choices数组中的第一个元素
            JSONArray choicesArray = responseObject.getJSONArray("choices");
            if (choicesArray == null || choicesArray.isEmpty()) {
                log.error("choices数组为空或不存在");
                return getDefaultScheduleList();
            }

            // 获取message中的content
            JSONObject firstChoice = choicesArray.getJSONObject(0);
            JSONObject message = firstChoice.getJSONObject("message");
            String content = message.getStr("content");

            log.info("请求结果：content = {}", content);

            // 解析content中的JSON数组
            JSONArray jsonArray = JSONUtil.parseArray(content);

            List<StudySchedule> list = JSONUtil.toList(jsonArray, StudySchedule.class);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            log.error("获取学习计划失败 e-> {}", e.getMessage());
            return getDefaultScheduleList();
        }
    }
}
